import { ref } from 'vue'

// 创建简单的事件总线
const eventBus = {
  // 存储事件处理函数
  events: {},
  
  // 订阅事件
  on(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = []
    }
    this.events[eventName].push(callback)
  },
  
  // 取消订阅
  off(eventName, callback) {
    if (!this.events[eventName]) return
    if (!callback) {
      this.events[eventName] = []
      return
    }
    this.events[eventName] = this.events[eventName].filter(
      cb => cb !== callback
    )
  },
  
  // 触发事件
  emit(eventName, ...args) {
    if (!this.events[eventName]) return
    this.events[eventName].forEach(callback => {
      callback(...args)
    })
  }
}

// 创建一个响应式的登录状态引用，可以在组件间共享
const authState = ref({
  isLoggedIn: !!localStorage.getItem('token'),
  user: null
})

// 尝试从localStorage中获取用户信息
try {
  const savedUser = localStorage.getItem('user')
  if (savedUser) {
    authState.value.user = JSON.parse(savedUser)
  }
} catch (error) {
  console.error('解析用户信息失败', error)
}

// 更新登录状态的方法
const updateAuthState = () => {
  const token = localStorage.getItem('token')
  authState.value.isLoggedIn = !!token
  
  try {
    const savedUser = localStorage.getItem('user')
    if (savedUser) {
      authState.value.user = JSON.parse(savedUser)
    } else {
      authState.value.user = null
    }
  } catch (error) {
    console.error('解析用户信息失败', error)
    authState.value.user = null
  }
  
  // 触发登录状态变化事件
  eventBus.emit('auth-changed', authState.value)
}

export { eventBus, authState, updateAuthState } 